package com.ziiwee.reduce.describe.types.impls;

import com.ziiwee.reduce.commons.utils.ReflectUtil;
import com.ziiwee.reduce.describe.TypeDescribe;
import com.ziiwee.reduce.describe.models.TypeDescribeModel;
import com.ziiwee.reduce.describe.types.TypeProvider;
import com.ziiwee.reduce.describe.types.TypeProviderContext;
import com.ziiwee.reduce.describe.utils.DescribeUtil;
import org.springframework.core.ResolvableType;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author ziiwee
 * @date 2020/8/13
 */
public class ArrayTypeProvider implements TypeProvider {
    @Override
    public boolean support(ResolvableType type) {
        return type.isArray() || ReflectUtil.isFromInterface(type.resolve(), Collection.class);
    }

    @Override
    public TypeDescribe render(ResolvableType type, TypeProviderContext context) {
        ResolvableType entity;
        if (type.isArray()) {
            entity = type.getComponentType();
        } else if (type.getGenerics().length == 1) {
            entity = type.getGeneric(0);
        } else {
            entity = ResolvableType.forClass(Object.class);
        }
        TypeDescribe entityType = context.render(entity);
        TypeDescribeModel list;
        if(entityType!=null){
            list = new TypeDescribeModel(
                    DescribeUtil.getSimpleNameByResolvableType(type),
                    type,
                    entityType.getLabel() + "列表",
                    null,
                    entityType.getFields()
            );
        }else{
            list = new TypeDescribeModel(
                    DescribeUtil.getSimpleNameByResolvableType(type),
                    type,
                    "列表",
                    null,
                    new ArrayList<>()
            );
        }
//        context.putCache(type.toString(), list);
        return list;
    }
}
